from  rest_framework.serializers import ModelSerializer
from apps.goods.models import Brand
from fdfs_client import client
from rest_framework.exceptions import ValidationError


class BrandModelSerializer(ModelSerializer):
    """品牌管理序列化器"""

    def create(self, validated_data):
        """重写序列化器的保存方法，进行fastdfs服务器的图片上传"""
        logo=validated_data.pop('logo')
        cli=client.Fdfs_client('utils/fastdfs/client.conf')
        img_data=cli.upload_by_buffer(logo.read())
        """
        {'Remote file_id': 'group1/M00/00/00/wKjlhFsTgJ2AJvG_AAAyZgOTZN0850.jpg', 
        'Uploaded size': '12.00KB',
        'Local file name': '/home/python/Desktop/images/0.jpg', 
        'Storage IP': '192.168.229.132',
        'Group name': 'group1', 
        'Status': 'Upload successed.'}
        """
        if img_data.get('Status') != 'Upload successed.':
            raise ValidationError('商品logo保存失败')
        brand=Brand.objects.create(name=validated_data['name'],first_letter=validated_data['first_letter'],logo=img_data['Remote file_id'])

        return brand

    def update(self, instance, validated_data):
        """重写序列化器的保存方法，进行fastdfs服务器的图片上传"""
        logo=validated_data.pop('logo')
        cli=client.Fdfs_client('utils/fastdfs/client.conf')
        img_data=cli.upload_by_buffer(logo.read())
        """
        {'Remote file_id': 'group1/M00/00/00/wKjlhFsTgJ2AJvG_AAAyZgOTZN0850.jpg', 
        'Uploaded size': '12.00KB',
        'Local file name': '/home/python/Desktop/images/0.jpg', 
        'Storage IP': '192.168.229.132',
        'Group name': 'group1', 
        'Status': 'Upload successed.'}
        """
        if img_data.get('Status') != 'Upload successed.':
            raise ValidationError('商品logo保存失败')
        brand=Brand.objects.filter(id=self.data.get('id')).update(name=validated_data['name'],first_letter=validated_data['first_letter'],logo=img_data['Remote file_id'])

        return brand
    class Meta:
        model = Brand
        fields=('id','name','logo','first_letter')
